/*
微信小程序监听网络状态
*/

import store from '@/store'
export const NETWORK_STATUS = {
    OFFLINE: 'offline',//无网
    POOR: 'poor',//弱网
    NORMAL: 'normal'//网络正常 
} 
export const DOWNLOAD_TIME = 2000;// 请求时长阈值 （超过判定为弱网
const MAX_COUNT = 10;//无网递归监听次数
let count = 0;
let dialogStatus = false;//提示弹窗打开状态(防重复弹窗)
const app = getApp();//小程序实例
let timer;
// #ifdef MP-WEIXIN
const imgBaseUrl = "https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com"
// #endif
import config from './config.js';
// #ifdef H5 
const imgBaseUrl = "/oss"
// #endif
//获取当前网络情况
function getNetworkType() {
    return new Promise((resolve) => {
        uni.getNetworkType({
            success(res) {
                resolve(res);
            },
            fail(err) {
                resolve(err);
            }
        })
    })
}

//主监听
const getNetworkStatus = (opt = {}) => {
    return new Promise(async (resolve, reject) => {
        let networkStatus = NETWORK_STATUS.NORMAL;
        let networkType = opt.networkType
        const hideTips = opt.hideTips || false
        try {
            //获取本机信号状态 
            if (!networkType) {
                networkType = (await getNetworkType()).networkType || '5g'; 
            }
            console.log('networkChange-networkType', networkType)
            if ([ 'unknown', 'none'].includes(networkType)) {//'unknown',
                //无网
                networkStatus = NETWORK_STATUS.OFFLINE
                emitNetworkStatus(networkStatus, hideTips);
                resolve(networkStatus);
                return
            }
            if (['2g'].includes(networkType)) {
                //2g 3g 视为弱网
                networkStatus = NETWORK_STATUS.POOR
                emitNetworkStatus(networkStatus, hideTips);
                resolve(networkStatus);
                return //通过本机信号可以判断出来无网或弱网结果，不向下执行请求时长监听
            }

            const startTime = +new Date();
            await resquestTest();//测试请求
            const requestTime = +new Date() - startTime;
            if (requestTime > DOWNLOAD_TIME) {
                //超时长视为弱网
                networkStatus = NETWORK_STATUS.POOR;
            }
            emitNetworkStatus(networkStatus, hideTips);
            resolve(networkStatus);
            return
        } catch (error) {
            //网络异常  视为无网 
            networkStatus = NETWORK_STATUS.OFFLINE;
            emitNetworkStatus(networkStatus, hideTips);
            resolve(networkStatus);
        }
    })
}
//请求测试
export function resquestTest() {
    return new Promise((resolve, reject) => {
        uni.request({
            url:config.baseUrl +'/test/ping',
            // url: imgBaseUrl + '/upload/20240111/7c0346f7099292dbb163af7dcc23e7cb.png',
            data: {

            },
            // responseType: 'arraybuffer',
            timeout: DOWNLOAD_TIME,
            success(res) {
                resolve(res);
            },
            fail(err) {
                console.log('resquestTest-fail',err);
                resolve(null)
            }
        })
    })

}


//网络验证与emit
export function emitNetworkStatus(status, hideTips = false) {
    const onlineStatusChange=(status)=>{
        // uni.$emit('onlineStatusChange', status);
        store.commit('system/setOnlineStatus',status)
       
    }

    try {
        const oldNetwordStatus = getApp().globalData.networkStatus;
        const onlineStatus = getApp().globalData.onlineStatus; 
        //若网络状态不相同，触发chang事件
        if (oldNetwordStatus !== status || !getApp().globalData.onlineStatus) {
            console.log('emitNetworkStatus',status,onlineStatus)
            getApp().globalData.networkStatus = status;
            // 通过全局的事件系统，将结果发送出去
            // uni.$emit('networkChange', status, oldNetwordStatus);
            // onlineStatusChange(status)
            if (onlineStatus && status != 'normal') {//&& !dialogStatus
                dialogStatus = true
                //在线模式但网络无网或弱网
                if (hideTips) {
                    getApp().globalData.onlineStatus = false;
                    onlineStatusChange(false)
                } else {
                    console.log('切换无网')
                    // 确定切换
                    getApp().globalData.onlineStatus = false;
                    onlineStatusChange(false)
               
                }

            }


            if (!onlineStatus && status == 'normal') {// && !dialogStatus
                dialogStatus = true
                //离线模式但网络正常了
                if (hideTips) {
                    getApp().globalData.onlineStatus = true;
                    onlineStatusChange(true)
                } else {
                    console.log('切换有网')
                    // 确定切换
                    getApp().globalData.onlineStatus = true;
                    onlineStatusChange(true)
               
                }

            }
        }

    } catch (error) {
        console.log('networkChange1error', error)
    }

}



function on(opt) {
    count = 0
    getNetworkStatus(opt)


    if (timer) {
        clearInterval(timer)
        timer = null
    }
    timer = setInterval(() => {
        getNetworkStatus({})
        count++;
        if (count > MAX_COUNT) {
            clearInterval(timer)
            timer = null
        }
    }, 5000)
}

function off() {
    clearInterval(timer);
    timer = null
}



export default {
    on,
    off,
    getNetworkStatus
}